package com.example.test2.activity;

import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;

import com.example.test2.R;
import com.example.test2.databinding.ActivityAddBuyBinding;
import com.example.test2.db.control.BuyDbController;
import com.example.test2.db.entity.Buy;
import com.example.test2.utils.ToastUtils;

// TODO: 2024/5/29 发采购
public class AddBuyActivity extends BaseActivity<ActivityAddBuyBinding> {

    @Override
    protected void initData() {
        super.initData();
        getBinding().titleBar.setTitle("发布采购");
    }

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().btSend.setOnClickListener(view -> {send();});
        getBinding().titleBar.setLeftIconOnClickListener(view -> {finish();});
    }

    private void send() {
        String name = getBinding().etName.getText().toString();
        String need = getBinding().etNeed.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(need)) {
            ToastUtils.getInstance().show(AddBuyActivity.this, "商品名称和需求量不能为空");
            return;
        }

        String type = getBinding().etType.getText().toString();
        if (TextUtils.isEmpty(type)) {
            type = "不限";
        }
        String from = getBinding().etFrom.getText().toString();
        if (TextUtils.isEmpty(from)) {
            from = "全国";
        }
        String to = getBinding().etTo.getText().toString();
        String comment = getBinding().etComment.getText().toString();

        Buy purchase = new Buy();
        purchase.setName(name);
        purchase.setNeed(need);
        purchase.setType(type);
        purchase.setFromAddress(from);
        purchase.setToAddress(to);
        purchase.setComment(comment);

        BuyDbController.getInstance(AddBuyActivity.this).insertOrReplace(purchase);
        ToastUtils.getInstance().show(AddBuyActivity.this, "发布成功");
        new Handler().postDelayed(() -> {
            finish();
        }, 500);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_add_buy;
    }

    @Override
    protected ActivityAddBuyBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityAddBuyBinding.inflate(layoutInflater);
    }
}